package com.lims.novel;

import com.lims.utils.FileUtil;
import lombok.Data;
import org.junit.platform.commons.util.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author limaosheng
 * @create 2022-04-06 9:41
 * @desc
 */
public class 三五 {
    //地址
    public final static String URL = "http://www.xkushu.info/35zwhtml/168/168843";

    /**
     * @author lmshe
     * @create 20:46 2018/8/22
     * @desc 获取小说主要信息
     */
    public static NovelDto getNovelMsg(String serialNum) {
        //获取网页html内容
        String date = getData(URL);
        if (StringUtils.isBlank(date)) {
            System.out.println("获取小说章节信息失败");
            return null;
        }
        System.out.println("小说章节信息：" + date);
        //解析分割小说主体内容
        NovelDto novelDto;
        try {
            String str = date;
            //小说dto
            novelDto = new NovelDto();
            novelDto.setNovelName(serialNum);
            //解析分割章节内容
            List<NovelChapterDto> NovelChapterList = new ArrayList<>();
            //切割list
            str = str.substring(str.indexOf("<div id=\"list\">") + "<div id=\"list\">".length(), str.indexOf("<div class=\"listend\"></div>"));
            str = str.substring(str.indexOf("<dl>") + "<dl>".length(), str.lastIndexOf("<dt>"));
            String[] chapterArr = str.split("</dd>");
            //遍历
            for (int i = 0; i < chapterArr.length; i++) {
                String s = chapterArr[i];
                if(!s.contains(".html")){
                    continue;
                }
                if(i < 110){
                    continue;
                }
                //加入列表
                NovelChapterDto novelChapterDto = new NovelChapterDto();
                String fff = s.substring(s.indexOf("title=\"") + "title=\"".length());
                String aaa = fff.substring(0,fff.indexOf("\""));
                novelChapterDto.setChapterName(aaa);
                String sss = s.substring(s.indexOf("=\"") + "=\"".length(), s.indexOf(".html"));
                novelChapterDto.setChapterSerialNum(sss);
                NovelChapterList.add(novelChapterDto);
            }
            novelDto.setNovelChapterList(NovelChapterList);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return novelDto;
    }

    /**
     * @author lmshe
     * @create 17:58 2018/8/23
     * @desc 获取章节内容 http://xx/14_14055/9194140.html
     */
    public static String getChapterContent(String serialNum, String chapterSerialNum) {
        String chapterContent = "";
        //获取网页html内容
        String date = getData(URL +"/" + chapterSerialNum + ".html");
        if (StringUtils.isNotBlank(date)) {
            try {
                String str = date.substring(date.indexOf("<div class=\"gg_read_content_up\"><script>read_content_up();</script></div>")
                        + "<div class=\"gg_read_content_up\"><script>read_content_up();</script></div>".length());
                chapterContent = str.substring(0, str.indexOf("</div"));
            } catch (Exception e) {
                System.out.println(URL +"/" + chapterSerialNum + ".html");
                System.out.println(date);
                e.printStackTrace();
            }
        }
        chapterContent = chapterContent.replaceAll(" ", "");
        chapterContent = chapterContent.replaceAll("&nbsp;&nbsp;&nbsp;&nbsp;", "\n");
        chapterContent = chapterContent.replaceAll("<br/>", "");
        return chapterContent;
    }

    /**
     * @author lmshe
     * @create 20:38 2018/8/22
     * @desc 模拟浏览器发出请求，并返回网页内容字符串
     */
    public static String getData(String urlStr) {
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            Thread.sleep(200);
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(true);
            //conn.setRequestProperty("content-type", "text/html");
            // 设置请求头信息，例如User-Agent
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
            conn.connect();
            InputStream is = conn.getInputStream();//拿到输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            String tempLine;
            while ((tempLine = br.readLine()) != null) {
                result.append(tempLine);
            }
            br.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            conn.disconnect();
        }
        return result.toString();
    }

    @Data
    public static class NovelChapterDto {
        /**
         * 章节名
         */
        private String chapterName;
        /**
         * 章节编号
         */
        private String chapterSerialNum;
    }

    @Data
    public static class NovelDto {
        /**
         * 小说名称
         */
        private String novelName;
        /**
         * 章节列表
         */
        private List<NovelChapterDto> NovelChapterList;
    }

    public static void main(String[] args) {
        //小说编号
        String serialNum = "4";
        NovelDto novelDto = getNovelMsg(serialNum);
        //生成小说目录
        String path = System.getProperty("user.dir") + "/log/" + novelDto.getNovelName();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        int i = 1;
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < novelDto.getNovelChapterList().size(); j++) {
            String chapterContent = getChapterContent(serialNum, novelDto.getNovelChapterList().get(j).getChapterSerialNum());
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if(j != 0 && j%10 == 0){
                sb.append(novelDto.getNovelChapterList().get(j).getChapterName());
                sb.append(chapterContent);
                sb.append("\n");
                try {
                    String resPath = path + "/" + i + ".txt";
                    System.out.println("文件地址：" + resPath);
                    FileUtil.write(resPath, sb.toString());
                } catch (Exception e) {
                    System.out.println("生成失败");
                }
                i++;
                sb = new StringBuilder();
            }else {
                sb.append(novelDto.getNovelChapterList().get(j).getChapterName());
                sb.append(chapterContent);
                sb.append("\n");
                if(j == novelDto.getNovelChapterList().size()-1){
                    sb.append(novelDto.getNovelChapterList().get(j).getChapterName());
                    sb.append(chapterContent);
                    sb.append("\n");
                    try {
                        String resPath = path + "/" + i + ".txt";
                        System.out.println("文件地址：" + resPath);
                        FileUtil.write(resPath, sb.toString());
                    } catch (Exception e) {
                        System.out.println("生成失败");
                    }
                }
            }
        }
    }
}
